package com.example.lt.interceptor;

import com.example.lt.constant.CommonConstant;
import com.example.lt.context.BaseContext;
import com.example.lt.pojo.entity.Consumer;
import com.example.lt.properties.JwtProperties;
import com.example.lt.service.ConsumerService;
import com.example.lt.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @Author 小涛Tao
 * @Date: 2024/05/30/22:31
 * version 1.0 注释：自定义拦截器来校验前端传过来的token（jwt令牌）
 **/
@Slf4j
@Component
@RequiredArgsConstructor
public class JwtTokenInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    private final ConsumerService consumerService;

    /**
     * 校验jwt令牌
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }

        //1、从请求头中获取令牌
        String token = request.getHeader(jwtProperties.getLoginTokenName());

        //2、校验令牌
        try {
            token = token.substring(7); // 去掉"Bearer "前缀
            log.info("jwt校验:{}",token);
            Claims claims = JwtUtil.parseJWT(jwtProperties.getLoginSecretKey(), token);
            Integer loginId = Integer.valueOf(claims.get(CommonConstant.USER_ID).toString()); // 当前登录者的id
            Consumer consumer = consumerService.getById(loginId);
            if (consumer == null) {
                response.setStatus(401);
                return false;
            }
            log.info("当前登录者是：{}", loginId);
            BaseContext.setCurrentId(loginId); // 把当前登录者的id存入到线程本地变量中
            //3、通过，放行
            return true;
        } catch (Exception ex) {
            //4、不通过，响应401状态码
            response.setStatus(401);
            return false;
        }
    }
}
